package org.dreamwork.jasmine2.parser;

import org.dreamwork.text.TextParser;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-2-4
 * Time: 15:48:35
 */
public class ExpressionParser extends TextParser {

    public ExpressionParser (String expression) {
        super (expression);
    }

    public String parse () {
        StringBuffer sb = new StringBuffer ();
        String limit = "<%";
        int lastPos = cursor;
        while (cursor < stream.length) {
            Segment s = this.skipUntil (limit);
            if (s != null) {
                lastPos = cursor;
                String expr = s.toString ().trim ();
                if (expr.length () > 0) {
                    if (sb.length () > 0) sb.append ("+");
                    if (limit.equals ("<%")) {
                        sb.append ('"').append (s).append ('"');
                    } else {
                        if (expr.charAt (0) == '#' || expr.charAt (0) == '=')
                            expr = expr.substring (1).trim ();
                        sb.append ('(').append (expr).append (')');
                    }
                }
            } else {
                if (sb.length () > 0) sb.append ('+');
                sb.append ('"').append (new String (stream, lastPos, stream.length - lastPos)).append ('"');
            }
            if ("<%".equals (limit)) limit = "%>";
            else limit = "<%";
        }
        String statement = sb.toString ();
//        statement = statement.replaceAll ("\\\"", "\\\\\"");
//        statement = '"' + statement + '"';
        return statement;
    }

    public static void main (String[] args) throws Exception {
        String s = "<%# DataBinder.eval (dataItem, \"id\")%>&title=<%#DataBinder.eval(dataItem,\"title\")%>&aaa=yy";
        ExpressionParser parser = new ExpressionParser (s);
        System.out.println (parser.parse ());
    }
}